<template>
    <div class="dh_classify">
        <div class="dh_c-content" v-if="pageingstate != 3">
            <!-- 查询 -->
            <div class="dh_c-c-inquire">

                <el-form v-if="level === 0" :model="kindinquire" ref="kindinquire" :inline="true" label-width="70px" class="dh_cci-form mb10 pl10 pr10">
                    <el-form-item label="查询项" class="mt20 mb20">
                        <el-select v-model="kindinquire.select" @change="estimate">
                            <el-option label="分类名称" value="1"></el-option>
                            <el-option label="分类ID" value="2"></el-option>
                            <el-option label="分类级别" value="3"></el-option>
                            <el-option label="下级分类" value="4"></el-option>
                        </el-select>
                    </el-form-item>

                    <el-form-item label="分类名称" v-if="kindinquire.select === '1'" class="mt20 mb20">
                        <el-input v-model="kindinquire.name" placeholder="请输入查询的分类名称"></el-input>
                    </el-form-item>

                    <el-form-item label="分类ID" v-else-if="kindinquire.select === '2'" class="mt20 mb20">
                        <el-input v-model="kindinquire.id" placeholder="请输入查询的分类ID"></el-input>
                    </el-form-item>

                    <el-form-item label="分类级别" v-else-if="kindinquire.select === '3'" class="mt20 mb20">
                        <el-select v-model="kindinquire.level" placeholder="选择查询分类级别">
                            <el-option label="大类" value="0"></el-option>
                            <el-option label="小类" value="1"></el-option>
                        </el-select>
                    </el-form-item>

                    <el-form-item label="下级分类" class="mt20 mb20" v-else>
                        <el-select v-model="kindinquire.topid">
                            <el-option v-for="(item,key) in kindselect" :key='key' :label="item.name" :value="item.id"></el-option>
                        </el-select>
                    </el-form-item>

                    <el-form-item class="mt20 mb20">
                        <el-button type="primary" @click="seekkind" class="p10 f18">查询</el-button>
                        <el-button type="danger" @click="requestkindall();for(var r in kindinquire) r != 'select' ? kindinquire[r] = '' : ''" class="p10 f18">取消查询</el-button>
                    </el-form-item>
                </el-form>

            </div>
            <!-- 列表数据 -->
            <div class="dh_c-c-list">
                <div class="bb1 mb10 pb10">
                    <button type="button" @click="level=0;requestkindall()" v-if="level!==0" class="pt5 pr10 pb5 pl10 br5 wh bc4a"><i class="el-icon-arrow-left"></i>返回</button>
                    <button type="button" @click="pageingstate=3;kindform.level=String(level);kindform.topid=topid" class="pt5 pr10 pb5 pl10 br5 wh bc4a">添加分类</button>
                </div>
                <table class="dh_ccl-table tc f14">
                    <thead>
                        <tr>
                            <th>分类ID</th>
                            <th>中文名称</th>
                            <th>
                                <span v-if="level === 0">详情</span>
                                <span v-else>英文名称</span>
                            </th>
                            <th>分类级别</th>
                            <th>上级分类</th>
                            <th>操作</th>
                        </tr>
                    </thead>
                    <tbody>
                        <tr v-for="(item,key) in kindlist" :key="key">
                            <td>{{item.id}}</td>
                            <td>{{item.name}}</td>
                            <td>
                                <button type="button" @click="topid=item.id;examine()" class="bc4a br5 wh pt5 pr10 pb5 pl10" v-if="level === 0">查看</button>
                                <span v-else>{{item.namee}}</span>
                            </td>
                            <td>{{item.level | levelstate}}</td>
                            <td>{{item.topid | topidfilter}}</td>
                            <td>
                                <button type="button" @click="outerVisible=true;for(var p in kindupdata)kindupdata[p] = item[p];kindupdata.key=key" class="bc4a br5 wh pt5 pr10 pb5 pl10">修改</button>
                                <button v-if="level!==0" @click="deletekind(item.id,key)" type="button" class="bcfd br5 wh pt5 pr10 pb5 pl10">删除</button>
                            </td>
                        </tr>
                    </tbody>
                </table>

                <!-- 分页 -->
                <div class="dh_ccl-block bt1 bcwh">
                    <el-pagination
                    @size-change="handleSizeChange"
                    @current-change="handleCurrentChange"
                    :current-page.sync="currentPage"
                    :page-sizes="[5, 10, 15, 20]"
                    :page-size="pagesize"
                    layout="total, sizes, prev, pager, next"
                    :total="total"
                    class=" pt5 pr10 pb5 pl10">
                    </el-pagination>
                </div>
            </div>
            <!-- 弹出层 -->
            <el-dialog title="修改员工信息" width="35%" top="13%" :lock-scroll="true" :center="true" :visible.sync="outerVisible">
                <p class="tc ff53 mb10">*默认值对应的是原始数据，不填写视为不修改</p>
                <el-form :model="kindupdata" ref="kindupdata" label-width="80px" class="dh_s-a-form">
                    <el-form-item label="类别归属">
                        <el-select placeholder="选择小类别归属" v-model="kindupdata.topid" :disabled="kindupdata.topid===0 ? true : false">
                            <el-option v-for="(item,key) in kindselect" :key="key" :label="item.name" :value="item.id"></el-option>
                        </el-select>
                    </el-form-item>
                    <el-form-item label="中文名称" prop="name">
                        <el-input v-model="kindupdata.name" placeholder="请输入分类的中文名称" clearable></el-input>
                    </el-form-item>

                    <el-form-item label="英文名称">
                        <el-form-item>
                            <el-input v-model="kindupdata.namee" placeholder="请输入分类的中文名称" clearable></el-input>
                        </el-form-item>
                    </el-form-item>
                </el-form>
                <div slot="footer" class="dialog-footer">
                    <el-button @click="outerVisible = false">取消</el-button>
                    <el-button type="primary" @click="updatakind">提交</el-button>
                </div>
            </el-dialog>

        </div>

        <!-- 添加新员工的部分 -->
        <div class="dh_c-addstaff" v-else>
            <div class="bb1 p10">
                <button type="button" @click="pageingstate = 0" class="wh p5 br5 f14 bc4a mr10">返回列表</button>
                添加分类<span class="f14 b00a ml10">*大分类每次只能添加一个，小分类一次能添加多个(需要对应的大分类名称进行添加）</span>
            </div>
            <el-form :model="kindform" ref="kindform" :rules="rules" label-width="80px" class="dh_s-a-form p20">
                <el-form-item label="分类选择">
                    <el-select placeholder="选择类别" v-model="kindform.level">
                        <el-option label="大类" value="0"></el-option>
                        <el-option label="小类" value="1"></el-option>
                    </el-select>
                </el-form-item>
                <el-form-item v-if="kindform.level === '1'" label="类别归属" prop="topid">
                    <el-select placeholder="选择小类别归属" v-model="kindform.topid">
                        <el-option v-for="(item,key) in kindselect" :key="key" :label="item.name" :value="item.id"></el-option>
                    </el-select>
                </el-form-item>
                <el-form-item label="分类名称" v-if="kindform.level === '0'" prop="name">
                    <el-col :span="7"><el-input v-model="kindform.name" placeholder="请输入大类的中文名称" clearable></el-input></el-col>
                </el-form-item>

                <el-form-item label="" v-else v-for="(item,key) in kindform.arrname" :key="key">
                    <label slot="label" v-if="key === 0"><span>分类名称</span></label>
                    <label slot="label" class="tc f30 b00a pl20" v-else><span @click="kindform.arrname.splice(key,1)"><i class='el-icon-remove-outline'></i></span></label>
                    <el-col :span="6">
                        <el-form-item :prop="'arrname.'+key+'.name'" :rules="{required: true, message:'中文名不能为空',trigger:'blur'}">
                            <el-input v-model="item.name" placeholder="请输入小分类的中文名称" clearable></el-input>
                        </el-form-item>
                    </el-col>
                    <el-col :span="1" class="tc">—</el-col>
                    <el-col :span="6">
                        <el-form-item :prop="'arrname.'+key+'.namee'" :rules="{required: true, message:'英文名不能为空',trigger:'blur'}">
                            <el-input v-model="item.namee" placeholder="请输入小分类的英文名称" clearable></el-input>
                        </el-form-item>
                    </el-col>
                    <el-col :span="11" v-if="key === kindform.arrname.length-1" class='f30 b00a pl20'><span @click="kindform.arrname.push({name:'',namee:''})"><i class="el-icon-circle-plus-outline"></i></span></el-col>
                </el-form-item>

                <el-form-item>
                    <el-button type="primary" @click="addstaff('kindform')">提交</el-button>
                    <el-button type="danger" @click="resetstaff('kindform')">重置</el-button>
                </el-form-item>
            </el-form>
        </div>

    </div>
</template>

<script>
const axios = require('axios');
let that
export default {
    components: {},
    data() {
        return {
            token: '',
            topid: '',
            kindlist:[],
            kindselect: [],
            // 查询的绑定值
            kindinquire:{
                select: '1',
                name: '',
                id: '',
                level: '',
                topid: '',
            },
            // 更新绑定的值
            kindupdata:{
                level:'',
                id: '',
                name: '',
                namee:'',
                topid:'',
            },
            //新增分类，小类没多少，新增大类东西比较多
            kindform:{
                level: '',
                name: '',
                topid:'',
                arrname: [
                    {name:'',namee:''}
                ]
            },
            rules:{
                name:[
                    { required: true, message: '请输入分类的名称', trigger: 'blur' },
                ],
                topid:[
                    { required: true, message: '请选择小类所属的大类', trigger: 'change' }
                ],
                'arrname[0].name':[
                    {required:true,message:'model不能为空',trigger:'blur'},
                    {pattern:/^[\u4E00-\u9FA5]+$/,message:'只能输入中文和数字',trigger:'blur'}
                ],
                'arrname[0].namee':[
                    { required: true, message: '请输入分类的英文名称', trigger: 'blur' },
                ],
            },
            outerVisible: false,
            innerVisible: false,
            level: 0,                           //用于查看、大类的英文名隐藏和判断添加时的选框默认值（vuex更适合后期可以加上）
            topid:'',                           //添加分类时用来用来判断所属分类的用的（默认值用户体验方面的vuex更适合后期可以加上）
            pageingstate: 0,                    //彩笔使用的分页状态管理（区分数据运行）
            currentPage: 1,						//分页的默认页数
            pagesize: 10,                       //单页条数
            total: 0,						    //总条数
            querystate: false,                  //彩笔写法二（查询的范围查询需要分页，页数又不相等只能用这个状态过度，开启状态查询页数赋值为1）
        };
    },
    filters:{
        levelstate(level){
            if(level === 0){
                level = '大类'
            }else{
                level = '小类'
            }
            return level
        },
        topidfilter(topid){
            if(topid === 0){
                topid = "最上级"
            }else{
                // console.log(that.kindselect)
                that.kindselect.filter((item) => {
                    if(item.id === topid){
                        topid = item.name
                    }
                })
            }
            return topid
        }
    },
    computed: {},
    watch: {},
    methods: {
        // 数据列表
        requestkindall(){
            let that = this;
            that.pageingstate === 1 ? that.currentPage = 1 : ''
            let data = {current:that.currentPage,size:that.pagesize,level:that.level};
            let updata = JSON.stringify(data);
            // console.log(updata)
            axios({
                method: 'post',
                url: '/api/kindAll/list',
                headers: {
                    'Content-Type': 'application/json',
                    'authorization': `Bearer ${JSON.parse(sessionStorage.getItem('token'))}`
                },
                data: updata
            }).then(resp=>{
                // console.log(resp)
                that.pageingstate = 0;
                that.kindlist = resp.data.data;
                that.total = resp.data.code;
                that.topid = resp.data.data[0].topid;
            }).catch(err=>{})
        },

        // 拿到所有的大分类用作添加小分类选项使用，
        async requestimage(){
            let that = this;
            let total = 10,select;
            for(var i=0;i<2;i++){
                let that = this;
                let data = {current:1,size:total,level:0};
                let updata = JSON.stringify(data);
                // console.log(updata)
                await axios({
                    method: 'post',
                    url: '/api/kindAll/list',
                    headers: {
                        'Content-Type': 'application/json',
                        'authorization': `Bearer ${JSON.parse(sessionStorage.getItem('token'))}`
                    },
                    data: updata
                }).then(resp=>{
                    // console.log(resp,resp.data.data)
                    if(i === 0){
                        resp.data.code <= 10 ? (
                            that.kindselect = resp.data.data.map((item)=>{
                                return {
                                    id: item['id'],
                                    name: item['name']
                                }
                            }),i = 2
                        ) : total = resp.data.code
                    }else{
                        that.kindselect = resp.data.data.map((item)=>{
                            return {
                                id: item['id'],
                                name: item['name']
                            }
                        }) 
                    }
                }).catch(err=>{})
            }
        },

        // 分页的函数
        handleSizeChange(val,index) {
            // console.log(`每页 ${val} 条`,index);
            let that = this;
            this.pagesize = val;
            if(that.pageingstate === 0){
                that.requestkindall()
            }else if(that.pageingstate === 1){
                that.seekkind()
            }else{return}
        },
        handleCurrentChange(val,index) {
            // console.log(`当前页: ${val}`,index);
            let that = this;
            that.currentPage = val
            if(that.pageingstate === 0){
                that.level === 0 ? that.requestkindall() : that.examine()
            }else if(that.pageingstate === 1){
                that.seekkind()
            }else{return}
        },

        //大类下面的小类
        examine(){
            let that = this;
            let data = {current:that.currentPage,size:that.pagesize,topid:that.topid};
            let updata = JSON.stringify(data);
            axios({
                method: 'post',
                url: '/api/kindAll/list',
                headers: {
                    'Content-Type': 'application/json',
                    'authorization': `Bearer ${JSON.parse(sessionStorage.getItem('token'))}`
                },
                data: updata
            }).then( resp=> {
                // console.log(resp)
                if(resp.data.data !== ''){
                    that.kindlist = resp.data.data;
                    that.total = resp.data.code;
                    that.level = 1;
                    that.topid = resp.data.data[0].topid;
                }else{this.$message('数据请求失败');}
            }).catch( err=> {})
        },

        // 查询搜索
        seekkind(){
            let that = this;
            if(that.kindinquire.select === "1" && that.kindinquire.name === ''){
                return that.$message({
                    showClose:true,
                    message: '分类名称不能为空',
                    type: 'warning'
                })                
            }else if(that.kindinquire.select === "2" && that.kindinquire.id === ''){
                return that.$message({
                    showClose:true,
                    message: '分类ID不能为空',
                    type: 'warning'
                })              
            }else if(that.kindinquire.select === "3" && that.kindinquire.level === ''){
                return that.$message({
                    showClose:true,
                    message: '分类级别不能为空',
                    type: 'warning'
                })              
            }else if(that.kindinquire.select === "4" && that.kindinquire.topid === ''){
                return that.$message({
                    showClose:true,
                    message: '下级分类不能为空',
                    type: 'warning'
                })              
            }else{
                that.pageingstate === 0 || that.querystate === true ? that.currentPage = 1 : ''
                let data = {current:that.currentPage,size:that.pagesize};
                for(var i in that.kindinquire){
                    that.kindinquire[i] !== '' && i !== "select" ? data[i] = that.kindinquire[i] : '';
                }
                let updata = JSON.stringify(data);
                axios({
                method: 'post',
                url: '/api/kindAll/list',
                headers:{
                    'Content-Type': 'application/json',
                    'authorization': `Bearer ${JSON.parse(sessionStorage.getItem('token'))}`
                },
                data: updata
                }).then( resp=> {
                    // console.log(resp)
                    that.kindlist = resp.data.data
                    that.total = resp.data.code;
                    that.pageingstate = 1;
                    that.querystate = false;
                    this.$message({
                        showClose: true,
                        message: '搜索到'+resp.data.code+'条数据',
                        type: 'success'
                    })
                }).catch( err=> {})
            }
        },

        // 添加新员工
        addstaff(formverify){
            let that = this;
            that.$refs[formverify].validate((valid)=>{
                if(valid){
                    let data = {};
                    if(that.kindform.level === '0'){
                        data.topid = 0;
                        for(var u in that.kindform){
                            if(u==='name' || u==="level"){
                                data[u] = that.kindform[u]
                            }
                        }
                        that.uploading(data) 
                    }else{
                        for(var u in that.kindform){
                            if(u==='topid' || u==="level"){
                                data[u] = that.kindform[u]
                            }
                        }
                        for(var o=0;o<that.kindform.arrname.length;o++){
                            data.name = that.kindform.arrname[o].name;
                            data.namee = that.kindform.arrname[o].namee;
                            that.uploading(data) 
                        }
                    }
                }else{return false}
            })
        },

        // 添加分类的统一方法
        uploading(data){
            let updata = JSON.stringify(data);
            axios({
                method: 'post',
                url: '/api/kindAll/add',
                headers: {
                    'Content-Type': 'application/json',
                    'authorization': `Bearer ${JSON.parse(sessionStorage.getItem('token'))}`
                },
                data: updata
            }).then( resp=> {
                // console.log(resp)
                if(resp.data.message === '请求成功'){
                    data.topid === that.kindlist[0].topid && that.kindlist.length < that.pagesize ? (
                        data.id = resp.data.data,
                        that.kindlist.push(data)) : '';
                        that.total += 1
                    that.$message({
                        showClose: true,
                        message: '添加成功，可以在对应的分类列表中中找到',
                        type: 'success'
                    })
                    that.pageingstate = 0
                    for(var j in that.kindform) j!== 'arrname' ? that.kindform[j] = '' : that.kindform[j] = [{name:'',namee:''}];
                }else{
                    that.$message.error('添加失败，请刷新页面或者重新登录')
                }
            }).catch( err=> {})
        },

        // 添加页的重置效果
        resetstaff(formName){
            that.$refs[formName].resetFields();
        },

        // 修改分类数据
        updatakind(){
            let that = this;
            let data = {}
            for(var o in that.kindupdata)
            o!=="key" && that.kindupdata[o]!=='' ? data[o] = that.kindupdata[o] : '';
            let updata = JSON.stringify(data)
            this.$confirm('请再确认一下提交信息，无误后点击提交即可完成修改','提示',{
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning',
                center: true
            }).then(()=>{
                that.outerVisible = false
                axios({
                    method: 'post',
                    url: '/api/kindAll/update',
                    headers:{
                        'Content-Type': 'application/json',
                        'authorization': `Bearer ${JSON.parse(sessionStorage.getItem('token'))}`
                    },
                    data: updata
                }).then( resp=>{
                    // console.log(resp)
                    // 请求成功后，通过判断分类是否修改，执行相应的操作，未修改修改名称，修改了在数组中删除该条数据
                    if(resp.data.data === '更新成功！'){
                        data.topid === that.kindlist[that.kindupdata.key].topid ? that.kindlist.splice(that.kindupdata.key,1,data) : that.kindlist.splice(that.kindupdata.key,1);
                    }else{
                        this.$message('请检查网络或者尝试刷新页面');
                    }
                }).catch(err=>{})
                this.$message({
                    type: 'success',
                    message: '修改成功'
                })

                // 数据同步
                if(data.level === 1){
                    let smalldata = {
                        current: 1,
                        size: 10,
                        kindAllid: that.kindupdata.id,       
                    }
                    let upsmalldata = JSON.stringify(smalldata)
                    axios({
                        method: 'post',
                        url: '/api/templateKind/list',
                        headers: {
                            'Content-Type': 'application/json',
                            'authorization': `Bearer ${JSON.parse(sessionStorage.getItem('token'))}`
                        },
                        data: upsmalldata
                    }).then( resp=> {
                        // console.log(resp)
                        let templateid = new Array();
                        resp.data.data.forEach(item => {
                            templateid.push(item.id)
                        });
                        that.synchronous(templateid);
                    }).catch( err=> {})
                }else{return}

            }).catch(()=>{
                this.$message({
                    type: 'info',
                    message:'已取消修改'
                })
            })
        },

        // 修改模板中的大小类名称
        async synchronous(smallid){
            let data = {name:that.kindupdata.name,namee:that.kindupdata.namee},updata;
            for(var r=0;r<smallid.length;r++){
                data.id = smallid[r];
                updata = JSON.stringify(data);
                await axios({
                    method: 'post',
                    url: '/api/templateKind/update',
                    headers: {
                        'Content-Type': 'application/json',
                        'authorization': `Bearer ${JSON.parse(sessionStorage.getItem('token'))}`
                    },
                    data: updata
                }).then( resp=> {
                    // console.log(resp)
                }).catch( err=> {})
            }
            // console.log(smallid)
        },

        // 删除
        deletekind(id,key){
            let that = this;
            let data = {id: id};
            let updata = JSON.stringify(data);
            this.$confirm('删除员工后相应的数据页无法找到，确定要删除吗？','提示',{
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning',
                center: true
            }).then(()=>{
                axios({
                    method: 'post',
                    url: '/api/kindAll/delete',
                    headers: {
                        'Content-type': 'application/json',
                        'authorization': `Bearer ${JSON.parse(sessionStorage.getItem('token'))}`
                    },
                    data: updata
                }).then( resp=> {
                    // console.log(resp)
                    if(resp.data.data === "删除成功！"){
                        that.kindlist.splice(key,1);
                        that.total--
                    }else{return}
                }).catch( err=> {})
                this.$message({
                    type: 'success',
                    message: '成功删除'
                })
            }).catch(()=>{
                this.$message({
                    type: 'info',
                    message:'已取消删除'
                })
            })
        },

        //协调查询的两个分为查找的条件的分页区分（判断两个范围查询的输入框内是否都存在值，都有开启查询）
        estimate(){
            let that = this;
            if(that.kindinquire.select === "3" && that.kindinquire.topid !== ''){
                that.querystate = true;
            }else if(that.kindinquire.select === "4" && that.kindinquire.level !== ''){
                that.querystate = true;
            }else{that.querystate = false}
            for(var r in that.kindinquire) r != 'select' ? that.kindinquire[r] = '' : ''
        },

        async requesttoken(){
            let that = this;
            let loguser = JSON.parse(sessionStorage.getItem('updata'))
            let data = {username:loguser.username, password:loguser.password};
            let updata = JSON.stringify(data);
            // console.log(updata)
            await axios({
                method: 'post',
                url: '/api/getAuthority/manager',
                headers: { 'Content-Type': 'application/json' },
                data: updata
            })
            .then( resp=> {
                // console.log(resp)
                that.token = resp.data.data;
                sessionStorage.setItem('token',JSON.stringify(resp.data.data))
                that.requestkindall();
                that.requestimage()
            }).catch( err=> {})
        }
    },
    created() {
        let that = this;
        that.requesttoken()
    },
    mounted() {
        // this.token = JSON.parse(sessionStorage.getItem('token'));
        },
    beforeCreate() {
        that = this;
    },
    beforeMount() {},
    beforeUpdate() {},
    updated() {},
    beforeDestroy() {},
    destroyed() {},
    activated() {},
    }
</script>
<style scoped>
.dh_classify{
    height: 100%;
}
.dh_c-content{
    display: flex;
    flex-direction: column;
    height: 100%;
}
/* 查询 */
.dh_cci-form{
    background-color: #ffffff;
    box-shadow: 0 0 2px #4b4b4b;
    border-radius: 5px;
}
/* 列表数据 */
.dh_c-c-list{
    display: flex;
    flex-direction: column;
    /* height: calc(100% - 91px); */
    height: 100%;
    padding: 10px;
    background-color: #ffffff;
    border-radius: 5px;
    box-sizing: border-box;
    box-shadow: 0 0 2px #4b4b4b;
}
.dh_ccl-table{
    width: 100%;
    border-collapse: collapse;
    border-bottom: 1px solid #e0e0e0;
    border-right: 1px solid #e0e0e0;
    border-spacing: 0;/*去掉单元格间隙*/
}
.dh_ccl-table th{
    background-color: #ececec;
}
.dh_ccl-table tbody tr:hover{
    background-color: #ececec;
}
.dh_ccl-table th,.dh_ccl-table td{
    padding: 10px 0;
    border-left:1px solid #e0e0e0;
    border-top:1px solid #e0e0e0;
}
/* 分页 */
.dh_ccl-block{
    margin-top: auto;
}

/* 加员工 */
.dh_c-addstaff{
    /* height: 100%; */
    background-color: #ffffff;
    border-radius: 5px;
    box-shadow: 0 0 3px #3d3d3d;
}
.el-form-item__label{
    border-bottom: 1px solid #e7e7e7;
}
</style>
<style>
/* 修改员工信息 */
.el-dialog--center .el-dialog__body{
    padding: 0 30px;
}
.el-dialog__body{
    padding: 0;
}
</style>